package com.fourool.goodsmall.service.impl;

import com.fourool.goodsmall.common.Result;
import com.fourool.goodsmall.service.SmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 定义Redis中key的前缀，防止key冲突
    private static final String KEY_PREFIX_CODE = "sms:code:";
    private static final String KEY_PREFIX_LIMIT = "sms:limit:";

    // 验证码有效期，5分钟
    private static final long CODE_EXPIRATION_MINUTES = 5;
    // 重复发送的冷却时间，60秒
    private static final long LIMIT_EXPIRATION_SECONDS = 60;

    @Override
    public Result sendCode(String phone) {
        String limitKey = KEY_PREFIX_LIMIT + phone;

        // 1. 防止60秒内重复发送
        if (redisTemplate.hasKey(limitKey)) {
            return Result.error(400, "请勿频繁操作");
        }

        // 2. 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(999999));

        String codeKey = KEY_PREFIX_CODE + phone;

        // 3. 将验证码和防刷标记存入Redis
        try {
            // 存储验证码，并设置5分钟过期
            redisTemplate.opsForValue().set(codeKey, code, CODE_EXPIRATION_MINUTES, TimeUnit.MINUTES);

            // 存储防刷标记，并设置60秒过期
            redisTemplate.opsForValue().set(limitKey, "1", LIMIT_EXPIRATION_SECONDS, TimeUnit.SECONDS);

            // 模拟发送到控制台
            log.info("向手机号 {} 发送验证码: {} (有效期{}分钟)", phone, code, CODE_EXPIRATION_MINUTES);

            // TODO 调用第三方短信服务接口

            return Result.success("验证码发送成功"); // 返回更明确的信息
        } catch (Exception e) {
            log.error("Redis操作失败: {}", e.getMessage());
            return Result.error(500, "服务异常，请稍后再试");
        }
    }

    @Override
    public boolean verifyCode(String phone, String code) {
        if (phone == null || code == null) {
            return false;
        }

        String codeKey = KEY_PREFIX_CODE + phone;
        String cachedCode = redisTemplate.opsForValue().get(codeKey);

        if (code.equals(cachedCode)) {
            // 验证成功后，立即删除key，防止重复使用
            redisTemplate.delete(codeKey);
            return true;
        }

        return false;
    }
}